<template>
	<div class="functionChart">
		<el-row v-if="isEdit"><h3 style="border-left: 3px solid blue; padding-left: 5px">当前节点</h3></el-row>
		<el-row v-if="isAdd"><h3 style="border-left: 3px solid blue; padding-left: 5px">添加节点</h3></el-row>
		<el-row>
			<el-col>
				<el-form :label-position="_this.labelPosition" :model="_this.curNode" label-width="110px">
					<el-form-item v-if="isAdd" label="上级编码">
						<span>{{ _this.curNode.ParentCode }}</span>
					</el-form-item>
					<el-form-item v-if="isAdd" label="本级编码">
						<el-input v-model="_this.curCode" style="width: 90%" placeholder="请输入当前级编码" />
					</el-form-item>
					<!-- <el-form-item label="节点编码"> -->
					<el-form-item :label="rootNode.Title + '名称'">
						<span>{{ _this.curNode.ParentCode + _this.curCode }}</span>
					</el-form-item>
					<!-- <el-form-item label="名称"> -->
					<el-form-item :label="rootNode.Title">
						<el-input v-model="_this.curNode.Title" style="width: 90%" :placeholder="'请输入' + rootNode.Title" />
					</el-form-item>

					<el-form-item v-if="_this.itemType && props.itemTypeDefine" :label="_this.itemType.title">
						<el-input v-if="props.itemTypeDefine.InputType == '0'" v-model="_this.itemType.value" style="width: 90%" placeholder="请输入" />
						<el-select v-if="props.itemTypeDefine.InputType == '1'" v-model="_this.itemType.value" style="width: 90%">
							<el-option v-for="(item, index) in props.itemTypeDefine.Options" :key="index" :label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>

					<div v-if="_this.extendFields.length > 0">
						<el-form-item v-for="(item, index) in _this.extendFields" :key="index" :label="item.title">
							<el-input v-model="item.value" style="width: 90%" placeholder="请输入" />
						</el-form-item>
					</div>

					<div v-if="props.useIcon">
						<el-form-item label="导航图标">
							<el-row style="display: flex; align-items: center">
								当前图标：
								<SvgIcon v-if="/^ele-.+/.test(_this.curNode.IconID)" :name="_this.curNode.IconID" :size="20" />
								<img v-else-if="/^http.+/.test(_this.curNode.IconID)" :src="_this.curNode.IconID" style="width: 30px" />
								<span>（选择或上传）</span>
								<el-button type="primary" @click="iconsVisible = true" style="margin-right: 10px">选择图标</el-button>
								<zUpload ref="zupload" :attrs="_this.attrs" v-model="_this.curNode.IconID" :showPlusIcon="false">
									<el-button type="primary" style="transform: translateY(5px)">点击上传</el-button>
								</zUpload>
							</el-row>
						</el-form-item>
					</div>

					<el-form-item label="是否发布">
						<el-switch v-model="_this.curNode.Status" active-color="#13ce66" inactive-color="#cecece" active-value="1" inactive-value="0" />
					</el-form-item>
				</el-form>
			</el-col>
		</el-row>
		<el-row>
			<el-col>
				<el-button v-if="_this.isEdit" type="primary" @click="submitUpdateNode">修改</el-button>
				<el-button v-if="_this.isEdit" type="primary" @click="closeUpdateNode">取消</el-button>
				<el-button v-if="_this.isAdd" type="primary" @click="submitAddNode">提交</el-button>
				<el-button v-if="_this.isAdd" type="primary" @click="closeAddNode">取消</el-button>
			</el-col>
		</el-row>

		<icons-dialog v-if="_this.iconsVisible" :iconsVisible="_this.iconsVisible" @select="nodeIcon" @clone="onCloseIcon" />
	</div>
</template>
<script setup>
// import { Post } from '/@/api/linxyun/base/index.ts'
import zUpload from '/@/components/Linxyun/FileClient/index.vue';
import IconsDialog from '/@/components/Linxyun/IconDialog/IconsDialog.vue';
import FileIns from '/@/components/Linxyun/FileClient/FileClientApi/file_instance';
import { ElMessage } from 'element-plus';
import { httpReqeustApi } from '/@/api/linxyun/base';

const httpReqeust = httpReqeustApi();
const props = defineProps({
	parentNode: { type: Object, default: null },
	useIcon: { type: Boolean, default: false },
	groupID: { type: String, default: null },
	inNode: {
		type: Object,
		default: () => {
			return { Status: '1' };
		},
	},
	itemTypeDefine: { type: Object, default: null },
	extDefines: { type: Array, default: null },
	events: { type: Object, default: null },
	rootNode: { type: Object, default: () => ({}) },
});
const _this = reactive({
	lastestCode: null, // 用来判断是否切换了节点
	isAdd: false,
	isEdit: false,
	curCode: '',
	curNode: {},
	srcStatus: null,
	itemType: null,
	extendFields: [],
	getMaxItemCode: 'treeDataMaxSubItemCode',
	updateFuncName: 'updateTreeData',
	insertFuncName: 'insertTreeData',
	labelPosition: 'left',
	iconsVisible: false,
	fileClient: null,
	attrs: { listType: 'text', limit: 1, drag: false, type: 'img' },
});

watch(props.inNode, () => {
	initDdata();
	console.log('[Debug][EditNode][watch]node info: ', _this.curNode, props.itemTypeDefine);
});

onBeforeMount(() => {
	console.log('ddddddddddd: ', props.parentNode, _this.curNode);
	_this.fileClient = FileIns.instance();
	_this.updateFuncName = props.parentNode?.OpDataInfo?.updateFuncName || _this.updateFuncName;
	_this.insertFuncName = props.parentNode?.OpDataInfo?.insertFuncName || _this.insertFuncName;
	_this.getMaxItemCode = props.parentNode?.OpDataInfo?.getMaxItemCode || _this.getMaxItemCode;
	initDdata();
	console.log('[Debug][EditNode]node info: ', _this.curNode, props.itemTypeDefine);
});

const initDdata = async () => {
	_this.isAdd = false;
	_this.isEdit = false;
	_this.curNode = JSON.parse(JSON.stringify(props.inNode));
	_this.curCode = '';
	_this.srcStatus = null;
	_this.itemType = null;
	_this.extendFields = [];

	if (props.parentNode !== null) {
		_this.isAdd = true;
		let params = {
			TreeType: props.parentNode.TreeType,
			SuperiorItemCode: props.parentNode.ItemCode,
		};
		if (props.parentNode.ItemType) {
			params.ItemType = props.parentNode.ItemType;
		}
		httpReqeust.Post(_this.getMaxItemCode, params, null).then((res) => {
			// let maxCode = ''
			if (res.Records && res.Records.length > 0 && res.Records[0].MaxCode !== '0' && res.Records[0].MaxCode.length > params.SuperiorItemCode.length) {
				// maxCode = res.Recodes[0].MaxCode
				const maxCodeTmp = res.Records[0].MaxCode.substr(params.SuperiorItemCode.length);
				console.log('maxCode:', maxCodeTmp);
				const maxVal = parseInt(maxCodeTmp);
				if (!isNaN(maxVal)) {
					const curCodeTmp = String(maxVal + 1);
					_this.curCode = curCodeTmp.padStart(4, '0');
				}
			} else if (res.Records && (res.Records[0].MaxCode === '0' || res.Records[0].MaxCode === '')) {
				_this.curCode = '0001';
			} else {
				// _this.curCode = '0001'
			}
			console.log(res);
		});
		// _this.curCode = props.parentNode.ItemCode
	} else {
		_this.isEdit = true;

		_this.srcStatus = null;
		if (_this.curNode.Status !== undefined) {
			_this.srcStatus = _this.curNode.Status;
		}
		if (_this.curNode.ParentCode === '') {
			_this.curCode = _this.curNode.ItemCode;
		} else {
			_this.curCode = _this.curNode.ItemCode.substr(_this.curNode.ParentCode.length);
		}
	}
	if (props.itemTypeDefine && props.itemTypeDefine.InputType) {
		_this.itemType = { title: props.itemTypeDefine.Name, value: _this.curNode.ItemType };
	}
	if (props.extDefines) {
		_this.extendFields = [];
		let extData = {};
		if (_this.curNode.Data && _this.curNode.Data !== '') {
			extData = JSON.parse(_this.curNode.Data.replace(/\\/g, ''));
		}
		for (let i = 0; i < props.extDefines.length; i++) {
			let value = extData[props.extDefines[i].key] || '';
			_this.extendFields.push({ fieldName: props.extDefines[i].key, title: props.extDefines[i].title, value: value });
		}
	}
};
const genNodeParams = () => {
	const params = {};
	params.ItemCode = _this.curNode.ItemCode;
	params.Level = _this.curNode.Level;
	params.TreeType = _this.curNode.TreeType;
	if (_this.itemType) {
		params.ItemType = _this.itemType.value;
	}
	params.Title = _this.curNode.Title;
	if (_this.curNode.IconID) {
		params.IconID = _this.curNode.IconID;
	}
	params.SuperiorItemCode = _this.curNode.ParentCode;
	params.Status = _this.curNode.Status;
	if (props.groupID) {
		params.GroupID = props.groupID;
	}
	if (_this.isAdd) {
		params.CreateTime = '_SysTime_';
		if (params.Status === '1') {
			params.PublishTime = '_SysTime_';
		}
	} else {
		if (_this.srcStatus && _this.srcStatus === '0' && params.Status === '1') {
			params.PublishTime = '_SysTime_';
		}
	}

	if (_this.extendFields && _this.extendFields.length > 0) {
		let tmp = {};
		for (let i = 0; i < _this.extendFields.length; i++) {
			tmp[_this.extendFields[i].fieldName] = _this.extendFields[i].value;
		}

		params.Data = JSON.stringify(tmp);
	}

	return params;
};
const submitAddNode = async () => {
	var Regx = /^[A-Za-z0-9\._]*$/;
	if (!Regx.test(_this.curCode) || _this.curCode.length === 0) {
		ElMessage({ message: '节点编码由点，下划线，英文字母或数字组成', type: 'error', duration: BASE_API.MSG_SHOW_TIME });
		return;
	}
	if (!Regx.test(_this.curCode) || _this.curCode.length === 0) {
		ElMessage({ message: '当前节点编码不能为空', type: 'error', duration: BASE_API.MSG_SHOW_TIME });
		return;
	}

	_this.curNode.ItemCode = _this.curNode.ParentCode + _this.curCode;
	const params = genNodeParams();
	if (params === null) {
		return;
	}

	console.log('[Debug][editNode]Add node: ', params);

	let res = await httpReqeust.SyncPost(_this.insertFuncName, params);
	if (!res || !res.code || res.code !== '0000') {
		ElMessage({ message: '添加失败', type: 'error', duration: BASE_API.MSG_SHOW_TIME });
	} else {
		ElMessage({ message: '添加成功', type: 'sucess', duration: BASE_API.MSG_SHOW_TIME });
		if (props.events && props.events.reloadTree) {
			props.events.reloadTree(_this.curNode.ItemCode);
		}
	}
};
const submitUpdateNode = async () => {
	console.log('被点击率');
	if (!_this.curNode.Title || _this.curNode.Title.length <= 0) {
		ElMessage({ message: '名称不能为空', type: 'error', duration: BASE_API.MSG_SHOW_TIME });
		return;
	}

	const params = genNodeParams();
	if (params === null) {
		return;
	}
	console.log('[Debug][editNode]update node: ', params);
	if (props.useIcon) {
		await uploadIcon();
	}
	params.IconID = _this.curNode.IconID;
	let res = await httpReqeust.Post(_this.updateFuncName, params);
	if (!res || !res.code || res.code !== '0000') {
		ElMessage({ message: '修改失败', type: 'error', duration: BASE_API.MSG_SHOW_TIME });
	} else {
		ElMessage({ message: '修改成功', type: 'sucess', duration: BASE_API.MSG_SHOW_TIME });
		if (props.events && props.events.reloadTree) {
			props.events.reloadTree(_this.curNode.ItemCode);
		}
	}
};
const closeUpdateNode = () => {
	if (props.events.onSelected) {
		props.events.onSelected(_this.curNode);
	}
};
const closeAddNode = () => {
	if (props.events.onSelected) {
		props.events.onSelected(props.parentNode);
	}
};
const nodeIcon = (icon) => {
	_this.curNode.IconID = icon;
};

const zupload = ref(null);
const uploadIcon = async () => {
	console.log('zuploadzupload', toRaw(zupload.value));
	const fileList = await zupload.value.uploadSubmit();
	console.log('uploadIcon', fileList);
	fileList.length ? (_this.curNode.IconID = fileList[0].url) : '';
};
const onCloseIcon = () => {
	_this.iconsVisible = false;
};
</script>
<style scoped>
.mix-tree-list {
	cursor: pointer;
	display: flex;
	flex-direction: column;
	padding-left: 30px;
}
.back {
	background: rgb(204, 204, 204);
}
.mix-tree-item {
	display: flex;
	align-items: center;
	font-size: 16px;
	color: #333;
	height: 0;
	opacity: 0;
	transition: 0.2s;
	position: relative;
}

.mix-tree-item.border {
	border-bottom: 1px solid #eee;
}
.mix-tree-item.show {
	height: 50px;
	opacity: 1;
}
.mix-tree-icon {
	/* width: 26px;
  height: 26px; */
	margin-right: 8px;
	opacity: 0.9;
}

.mix-tree-item.showchild:before {
	transform: rotate(90deg);
}
.mix-tree-item.last:before {
	opacity: 0;
}
.title {
	max-width: 100%;
	margin-right: 40px;
}
.main {
	height: 100%;
	display: flex;
	justify-content: space-between;
	/* 设置超出滚动 */
	overflow-x: auto;
}
.list {
	margin: 15px;
	margin-left: 0;
}
:deep(.el-collapse-item__wrap) {
	overflow: auto !important;
}

:deep(.hide) {
	display: flex;
	transform: translateY(-5px);
}
</style>
